import base from './base';
import { getAntd ,getEcCom,getLabel } from './convert';
import trim from "lodash/trim";
import * as _ from "./public/common";

//校验签字意见并提示
export const verifyRemark = (params = {}) =>{
    let {needCheck = false , src = '', needPrompt = true,isaffirmance = '0',actiontype = '', isAddSign,isaffirmanceSrc} = params;
    const { commonParam,markInfo,submitParam,changeSubmitParam } = base.globalStore;
    const  {propFileCfg={}}  =base.layoutStore;
    const { intervenorright,isHideInput } = commonParam;
    const { isSignMustInput, isFormSignature,signMustInputTypes,remark} = markInfo;
    let needVeiryRequired = false;
    if(isHideInput != "1" || intervenorright > 0){
        if(!needCheck) needCheck = !(src == 'save' && actiontype == 'requestOperation') || isaffirmance == "1";
        if((isSignMustInput == "1" && needCheck) || (isSignMustInput == '2' && verifyRemarkMustInput(src,actiontype,needCheck,isaffirmanceSrc)))
            needVeiryRequired = true;
    }
    //保存签章及验证必填
    if(isFormSignature == "1"){
        return saveFormSignature(needVeiryRequired);
    }
    const CKHasLoad = !!(window.CK_REF && window.CK_REF.remark);
    const CKHasLoad_freeWfSimple = !!(window.CK_REF && window.CK_REF.freeWorkflowSimple);
    let result = true;
    //验证签字意见必填
    if(isHideInput != "1" || intervenorright > 0){
        let remarkContent = CKHasLoad ? window.CK_REF.remark.getData() : submitParam.remark;

        if(!remarkContent&&propFileCfg.openSeeIncome==1){
            remarkContent=remark;
        }
        if(isAddSign == 1)
            remarkContent = CKHasLoad_freeWfSimple ? window.CK_REF.freeWorkflowSimple.getData() : submitParam.remark;
        if(needVeiryRequired){
            result = chekcremark(remarkContent);
        }
        if(result && CKHasLoad) {
            let _remark = appendDefaultSytle(remarkContent);
            changeSubmitParam({remark:_remark});
        }
    }
    if(result === false && needPrompt){   //直接提示签字意见未填写
        const { message } = getAntd();
        message.warning(getLabel(386186,'"签字意见"未填写'),2);
        if(CKHasLoad && isAddSign != 1){
            const {controlVariableMap} = base.globalStore;
            controlVariableMap('isShowSignInput',true);
            controlVariableMap('isEditorFocus',true);
            signMustInputTips();
        }
    }
    return result;
}

//提交保存签章
const saveFormSignature = (needVeiryRequired) => {
    const { changeSubmitParam } = base.globalStore;
    let result = true;
    const { message } = getAntd();
    if(typeof window.saveAutographMul === "object"){
        let requestlogid="";
        if(window.saveAutographMul && window.saveAutographMul.wfWeaAutographCompremark){
            requestlogid = window.saveAutographMul.wfWeaAutographCompremark(needVeiryRequired)
        }
        if(requestlogid === true||(requestlogid == -1 && needVeiryRequired == false)){
            result = true;
        }else if(!isNaN(requestlogid) && parseInt(requestlogid) > 0){
            changeSubmitParam({workflowRequestLogId:requestlogid});
        }else{
            if(requestlogid == "-2")
                message.warning(getLabel(386186,'"签字意见"未填写'), 2);
            else
                message.warning(getLabel(528568,"签章保存失败"), 2);
            result = false;
        }
    }else{
        message.warning(getLabel(528569,"签章组件未加载成功"));
        result = false;
    }
    return result;
}

/**
 * 设置默认字体
 */
export const appendDefaultSytle = (_remark = '') => {
    if(_remark) {
        const preReg = new RegExp(
            /^<div id=\"wea_rich_text_default_font\"[^>]+\>/
        );
        if(preReg.test(_remark)) return _remark;
        const {markInfo = {} } = base.globalStore;
        const {extendParams = {},use_textarea_signinput= 0} = markInfo;
        const {wfSignDefaultFontFamily = '',wfSignDefaultFontSize = ''} = extendParams;
        //设置
        let defaultStyle = '';
        if(wfSignDefaultFontFamily && wfSignDefaultFontFamily.indexOf('/') > -1) {
            defaultStyle += `font-family:${wfSignDefaultFontFamily.split('/')[1]};`;
        }
        if(wfSignDefaultFontSize && wfSignDefaultFontSize.indexOf('/') > -1) {
            defaultStyle += `font-size:${wfSignDefaultFontSize.split('/')[1]};`;
        }
        if (defaultStyle) {
            if(use_textarea_signinput == 1) {
                _remark = `<span id="wea_rich_text_default_font" style="${defaultStyle}">${_remark}</span>`;
            } else {
                _remark = `<div id="wea_rich_text_default_font" style="${defaultStyle}">${_remark}</div>`;
            }

        }
    }
    return _remark;
}

//签字意见获取光标，并滚动签字意见框到可视区域
export const signMustInputTips = () =>{
    //处理意见在表单和不在表单问题
    let  remarktop = parseInt(jQuery("#remark").offset().top);
    if(remarktop == 0 && jQuery(".wf-req-sign-input")){
        remarktop = parseInt(jQuery(".wf-req-sign-input").offset().top);
    }
    let scrolltop = 0;
    const scrollDom = jQuery('.wf-req-form-scroll');
    const topDom = jQuery('.wea-new-top-req');
    //判断意见框是否在可视区域
    const isVisual = remarktop > 0 && (remarktop - topDom.height() + 200 <  scrollDom.height());
    if(!isVisual) {
        //意见输入框在底部要滚动到可视区域
        if(remarktop - topDom.height() + 200 > scrollDom.height()){
            scrolltop = remarktop + scrollDom.scrollTop() - 185;
        }
        //意见输入框在顶部要滚动到可视区域
        if(remarktop <  (topDom.height())){
            if(remarktop < 0) remarktop = remarktop * -1;
            scrolltop = scrollDom.scrollTop() - remarktop - topDom.height() -100;
        }
        console.log({scrolltop});
        setTimeout(()=>{
            scrollDom.animate({ scrollTop: scrolltop + "px" }, 0)
        },100);

    }
    window.CK_REF.remark.getEditor().focus();
}

//签字意见验证
export const chekcremark = (remarkcontent) => {
    const { submitParam } = base.globalStore;
    const {signworkflowids="", signdocids="", handWrittenSign=0} = submitParam;
    let hasvalue = true;
    if(signworkflowids.length > 0 || signdocids.length > 0 || (submitParam["field-annexupload"] || []).length > 0 || handWrittenSign > 0) {

    } else if(remarkcontent == null){
        hasvalue = false;
    }else {
        let _remarkcontent = remarkcontent;
        _remarkcontent = _remarkcontent.replace(/<p>/ig,'').replace(/<\/p>/ig,'').replace(/ /ig, "").replace(/&nbsp;/ig, "").replace(/<br \/>/ig,"");
        _remarkcontent = _remarkcontent.replace(/\\n/ig, "");
        if(trim(_remarkcontent).length  === 0) {
            hasvalue = false;
        }
    }
    return hasvalue;
}

//验证意见是否必填
export const verifyRemarkMustInput = (src = '',actionType = '',needCheck = false,isaffirmanceSrc = 'submit') => {
    const { markInfo = {},rightMenu = {} } = base.globalStore;
    const { signMustInputTypes = []} = markInfo;
    if('save' === src) {
        if(actionType === 'requestOperation') {
            if(needCheck) {
                return signMustInputTypes.indexOf(isaffirmanceSrc) > -1;
            }
            return false;
        } else {
            const {remarkOperationType = ''} = rightMenu;
            return signMustInputTypes.indexOf(remarkOperationType) > -1
        }
    }
    return signMustInputTypes.indexOf(src) > -1;
}

/**
 * 意见框是否显示必填标识
 * @return {boolean}
 */
export const needMustInputDot = () => {
    const { markInfo = {}, rightMenu ={} } = base.globalStore;
    let {rightMenus = [],remarkOperationType = ''} = rightMenu;
    const {signMustInputTypes = [],isSignMustInput} = markInfo;

    //['systemMenuType',]
    const remarkOperationIndex = _.findIndex(rightMenus,(o) => {
        if(o.type == 'BTN_DOINTERVENOR') remarkOperationType = 'intervenor';
        return ['POSTIL_FORWARD','POSTIL_CC','REPLY','CHUANYUE_REC'].indexOf(o.systemMenuType) > -1 || o.type == 'BTN_DOINTERVENOR';
    });
    let remarkMustInput  = isSignMustInput == '1';
    if(isSignMustInput == '2') {
        //非批注操作
        if(signMustInputTypes.indexOf('submit') > -1 && rightMenus.length > 0 && remarkOperationIndex == -1) {
            remarkMustInput = true;
        }
        //批注时必填
        if(remarkOperationIndex > -1 && signMustInputTypes.indexOf(remarkOperationType) > -1) {
            remarkMustInput = true;
        }
    }
    return remarkMustInput;
}

export const convertSpecialChar = str => {
    str = str.toString();
    str = str.replace(/<br>/gi, "\n");
    str = str.replace(/&nbsp;/gi, " ");
    str = str.replace(/&lt;/gi, "<");
    str = str.replace(/&gt;/gi, ">");
    str = str.replace(/&quot;/gi, '"');
    str = str.replace(/&amp;/gi, "&");
    return str;
  };

/**
 * 处理打印模板中手写签批图片样式
 */
export const handWritingHander = (nodeMark = '') => {
    let nodeMarkTemp = nodeMark;
    let reg = /<img.*?(\/>|<\/img>)/g;
    let images = nodeMarkTemp.match(reg);
    images && images.map((v) => {
        let oldclass = "";
        if(/class=(\"|\')(.*?)(\"|\')/g.test(v)) {
            oldclass = RegExp.$2;
        }
        if("handWrittenSign" == oldclass){
            let _v = v.replace(/<img/g, `<img onload='window.handWritingHander(this)'`);
            nodeMarkTemp = nodeMarkTemp.replace(v, _v);
        }
    })
    return nodeMarkTemp;
};

